package com.study.lilhan.niuke.demo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @Author: lihan
 * @Date : 2021/12/14- 12
 * @DESCRIPTION: com.study.lilhan.niuke.demo
 * @version: 1.0
 */
public class My37 {
    //[[10,30],[20,60],[80,100],[150,180]]
    public static void main(String[] args) {
        Interval interval = new Interval(1, 4);
        Interval interval2 = new Interval(0, 2);
        ArrayList<Interval> list= new ArrayList<Interval>();
        list.add(interval);
        list.add(interval2);
        ArrayList<Interval> arrayList = merge(list);
        System.out.println(arrayList);
    }

    public static  ArrayList<Interval> merge(ArrayList<Interval> intervals) {

        ArrayList<Interval> result = new ArrayList<>();
        intervals.sort( (obj1,obj2)->{
            return obj1.start -obj2.start;
        });
        int len = intervals.size();
        for (int i = 0; i < len; ) {
            Interval interval = intervals.get(i);
            if(i == len-1){
                result.add(interval);
                break;
            }
            Interval temp = intervals.get(++i);
            while ( i<len && interval.end >= temp.start){
                if(temp.end > interval.end){
                    interval.end = temp.end;
                }
                if(++i < len){
                    temp = intervals.get(i);
                }

            }
            result.add(interval);

        }

        return result;
    }


}
 class Interval {
     int start;
      int end;
     Interval() { start = 0; end = 0; }
      Interval(int s, int e) { start = s; end = e; }

     @Override
     public String toString() {
         return "{" +
                 + start +
                 "," + end +
                 '}';
     }
 }